package cn.lijigou.shopping;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.text.ChoiceFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.logging.LogRecord;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import cn.lijigou.shopping.domain.Advertising;
import cn.lijigou.shopping.domain.MLocation;
import cn.lijigou.shopping.domain.MResult;
import cn.lijigou.shopping.domain.Shop;
import cn.lijigou.shopping.service.LocationService;
import cn.lijigou.shopping.service.MSystem;
import cn.lijigou.shopping.service.ServerService;
import cn.lijigou.shopping.util.GetSingleThreadPool;
import cn.lijigou.shopping.util.Util;
import cn.lijigou.shopping.views.ImageAdsGallery;
import android.R.integer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnDismissListener;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.MailTo;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class HomeActivity extends MActivity implements  OnClickListener ,OnTouchListener,OnItemClickListener,OnCheckedChangeListener{
	    
	private EditText search_content = null;
	private Button search_btn;
	private View hotPlace = null;
	private TextView dialog_title;
	private TimerTask timerTask;
	private Timer searchtimer;
	public static  View search_view;
	public Boolean isFirst = true;

	private Timer   timer= null;
	private ListView searchListView;
	private String  versionData;
	public  String  area="";
	public  String  selectCity="";
	public  String  areaName="";
	public  String  record;
	
	private LinearLayout leftView;
	private Boolean search=true;
	private SharedPreferences preFerence;
	private String[] recordSearh=new String[]{};
	private boolean  isVersion;
	
	static int num=11;
    private static  Timer bottomTimer;
    public static Boolean isShow=false;
    public static View  bottom_line;
    static TextView  bottom_text;
    static int locating=11;
	
	private Map<Integer,ImageView> imageLeftMap;
	private Map<Integer,TextView>  textleftMap;
	private Map<Integer,TextView>  textleft_ToMap;
	private Map<Integer,ImageView> imageRightMap;
	private Map<Integer, Integer>  imagePosition;
	
	private static TextView BTNcity = null;
	public static Gallery imageAdsGallery;
    public static int i=0;
	private static TextView TVtitle = null;
	public static Dialog mDialog;
	public static PopupWindow mPop;;
	public static int size;
	public static CheckBox checkBox;
	public static TextView updateInfo;
	public static LinearLayout layout_shortcut;
	public static View mView;
	public static MainTabActivity parentMainTab;
	public static SearchAdapter searchAdapter;
	public static int dataType=1;
	
	public static int tempdataType=1;
	public static Boolean refreshAds=true;
	public static ImageView[] originViews;
	public static List<Advertising>  adsList;
	public static List<Drawable> adsDrawableList;
	public static ImageAdapter imageAdapter;
	public static List<String> mHot=new ArrayList<String>();
	public static List<String> recordError=new ArrayList<String>();
	public static  List<List<Shop>> dataSource = new ArrayList<List<Shop>>();
	public static int[] dataPage = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
	public static boolean[] isload = {true,true,true,true,true,true,true,true,true,true,true,true,true,true,true};
    private Integer[] leftPressedImages={R.drawable.left_pressed_1,R.drawable.left_pressed_2,R.drawable.left_pressed_3,R.drawable.left_pressed_4,R.drawable.left_pressed_5,R.drawable.left_pressed_6,R.drawable.left_pressed_7,R.drawable.left_pressed_8,R.drawable.left_pressed_9,R.drawable.left_pressed_10,R.drawable.left_pressed_11,R.drawable.left_pressed_12};
    private Integer[] leftNormalImages={R.drawable.left_normal_1,R.drawable.left_normal_2,R.drawable.left_normal_3,R.drawable.left_normal_4,R.drawable.left_normal_5,R.drawable.left_normal_6,R.drawable.left_normal_7,R.drawable.left_normal_8,R.drawable.left_normal_9,R.drawable.left_normal_10,R.drawable.left_normal_11,R.drawable.left_normal_12};
    private ExecutorService executorService = GetSingleThreadPool.getInstance();
    
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		overridePendingTransition(R.anim.push_in,R.anim.push_out);
		statistics(this);
		setViews();
		setCity();
        
        
	}

	private void statistics(final HomeActivity home) {
		// TODO Auto-generated method stub
		executorService.execute(new Thread() {
			
			public void run() {
				// TODO Auto-generated method stub
				MResult mResult = MSystem.open(home);
				if (mResult != null) {
					versionData = mResult.data;
					isVersion = mResult.isSuccess();
					mHander.sendEmptyMessage(0);
				}
			}

		});
	}
	 
	private void showUpdate(){
		new AlertDialog.Builder(this)
		.setIcon(R.drawable.icon)
		.setTitle(R.string.upgrade_tips)
		.setCancelable(false)
		.setMessage(versionData)
		.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Uri uri = Uri.parse("http://www.lookoo.cn/tuangou.apk");
				if(uri == null) {
					return ;
				}
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				startActivity(intent);
				
				dialog.dismiss();
			}
		})
		.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		})
		.create().show();
	}
	private void setCity() {
			  TimerTask task = new TimerTask() { 
					public void run() { 
						 if(!"".equals(MSystem.selectCity)){//如果用户选择了城市  就不在自动显示城市
							 selectCity = MSystem.selectCity;
							 timer.cancel();
						 }else if(MSystem.mLocation!=null){
							mTimeoutHandler.sendEmptyMessage(3);
							selectCity=MSystem.mLocation.getCity();
							MSystem.selectCity=MSystem.mLocation.getCity();
							timer.cancel();
						}
					} 
				}; 
			 timer = new Timer(); 
			 timer.schedule(task,0,1500);
	}
	private void  setViews(){
		preFerence=this.getSharedPreferences("user",MODE_PRIVATE);
		record = preFerence.getString("recordSearh","");
		adsDrawableList=new ArrayList<Drawable>();
		adsDrawableList.add(this.getResources().getDrawable(R.drawable.homeload_small));
		adsDrawableList.add(this.getResources().getDrawable(R.drawable.homeload_small));
		adsList=new ArrayList<Advertising>();
		imageAdapter=new ImageAdapter(this);
		imageAdsGallery=(ImageAdsGallery)this.findViewById(R.id.imageAdsGallery);
		imageAdsGallery.setAdapter(imageAdapter);
		imageAdsGallery.setOnItemClickListener(new HomeOnItemClick());
	//获取广告
		parentMainTab=(MainTabActivity)this.getParent();
	//循环播放广告
		timerTask = getAdvertisingTask();
		Timer timer=new Timer();
		timer.schedule(timerTask, 0,6000);
		
		ImageView OriginOne= (ImageView)this.findViewById(R.id.OriginOne);
        ImageView OriginTwo= (ImageView)this.findViewById(R.id.OriginTwo);
        ImageView OriginThree= (ImageView)this.findViewById(R.id.OriginThree);
        ImageView OriginFour= (ImageView)this.findViewById(R.id.OriginFour);
        ImageView OriginFive= (ImageView)this.findViewById(R.id.OriginFive);
        originViews=new ImageView[]{OriginOne,OriginTwo,OriginThree,OriginFour,OriginFive};
        setOriginViews();
		
		View button_open001  = (View) findViewById(R.id.button_open001);
		View button_open002  = (View) findViewById(R.id.button_open002);
		View button_open003  = (View) findViewById(R.id.button_open003);
		View button_open004  = (View) findViewById(R.id.button_open004);
		View button_open005  = (View) findViewById(R.id.button_open005);
		View button_open006  = (View) findViewById(R.id.button_open006);
		View button_open007  = (View) findViewById(R.id.button_open007);
		View button_open008  = (View) findViewById(R.id.button_open008);
		View button_open009 = (View) findViewById(R.id.button_open009);
		View button_open0010  = (View) findViewById(R.id.button_open010);
		
		button_open001.setOnClickListener(this);
		button_open002.setOnClickListener(this);
		button_open003.setOnClickListener(this);
		button_open004.setOnClickListener(this);
		button_open005.setOnClickListener(this);
		button_open006.setOnClickListener(this);
		button_open007.setOnClickListener(this);
		button_open008.setOnClickListener(this);
		button_open009.setOnClickListener(this);
		button_open0010.setOnClickListener(this);
		
		button_open001.setOnTouchListener(this);
		button_open002.setOnTouchListener(this);
		button_open003.setOnTouchListener(this);
		button_open004.setOnTouchListener(this);
		button_open005.setOnTouchListener(this);
		button_open006.setOnTouchListener(this);
		button_open007.setOnTouchListener(this);
		button_open008.setOnTouchListener(this);
		button_open009.setOnTouchListener(this);
		button_open0010.setOnTouchListener(this);
		
		ImageView imageleft1  = (ImageView) findViewById(R.id.Imageleft1);
		ImageView imageleft2  = (ImageView) findViewById(R.id.Imageleft2);
		ImageView imageleft3  = (ImageView) findViewById(R.id.Imageleft3);
		ImageView imageleft4  = (ImageView) findViewById(R.id.Imageleft4);
		ImageView imageleft5  = (ImageView) findViewById(R.id.Imageleft5);
		ImageView imageleft6  = (ImageView) findViewById(R.id.Imageleft6);
		ImageView imageleft7  = (ImageView) findViewById(R.id.Imageleft7);
		ImageView imageleft8  = (ImageView) findViewById(R.id.Imageleft8);
		ImageView imageleft9  = (ImageView) findViewById(R.id.Imageleft9);
		ImageView imageleft10  = (ImageView) findViewById(R.id.Imageleft10);
		imageLeftMap=new HashMap<Integer, ImageView>();
		imageLeftMap.put(R.id.button_open001, imageleft1);
		imageLeftMap.put(R.id.button_open002, imageleft2);
		imageLeftMap.put(R.id.button_open003, imageleft3);
		imageLeftMap.put(R.id.button_open004, imageleft4);
		imageLeftMap.put(R.id.button_open005, imageleft5);
		imageLeftMap.put(R.id.button_open006, imageleft6);
		imageLeftMap.put(R.id.button_open007, imageleft7);
		imageLeftMap.put(R.id.button_open008, imageleft8);
		imageLeftMap.put(R.id.button_open009, imageleft9);
		imageLeftMap.put(R.id.button_open010, imageleft10);
		
		TextView textleft1  = (TextView) findViewById(R.id.textleft1);
		TextView textleft2  = (TextView) findViewById(R.id.textleft2);
		TextView textleft3  = (TextView) findViewById(R.id.textleft3);
		TextView textleft4  = (TextView) findViewById(R.id.textleft4);
		TextView textleft5  = (TextView) findViewById(R.id.textleft5);
		TextView textleft6  = (TextView) findViewById(R.id.textleft6);
		TextView textleft7  = (TextView) findViewById(R.id.textleft7);
		TextView textleft8  = (TextView) findViewById(R.id.textleft8);
		TextView textleft9  = (TextView) findViewById(R.id.textleft9);
		TextView textleft10  = (TextView) findViewById(R.id.textleft10);
		textleftMap=new HashMap<Integer, TextView>();
		textleftMap.put(R.id.button_open001, textleft1);
		textleftMap.put(R.id.button_open002, textleft2);
		textleftMap.put(R.id.button_open003, textleft3);
		textleftMap.put(R.id.button_open004, textleft4);
		textleftMap.put(R.id.button_open005, textleft5);
		textleftMap.put(R.id.button_open006, textleft6);
		textleftMap.put(R.id.button_open007, textleft7);
		textleftMap.put(R.id.button_open008, textleft8);
		textleftMap.put(R.id.button_open009, textleft9);
		textleftMap.put(R.id.button_open010, textleft10);
		TextView textleft_to1  = (TextView) findViewById(R.id.textleft_to1);
		TextView textleft_to2  = (TextView) findViewById(R.id.textleft_to2);
		TextView textleft_to3  = (TextView) findViewById(R.id.textleft_to3);
		TextView textleft_to4  = (TextView) findViewById(R.id.textleft_to4);
		TextView textleft_to5  = (TextView) findViewById(R.id.textleft_to5);
		TextView textleft_to6  = (TextView) findViewById(R.id.textleft_to6);
		TextView textleft_to7  = (TextView) findViewById(R.id.textleft_to7);
		TextView textleft_to8  = (TextView) findViewById(R.id.textleft_to8);
		TextView textleft_to9  = (TextView) findViewById(R.id.textleft_to9);
		TextView textleft_to10  = (TextView) findViewById(R.id.textleft_to10);
		textleft_ToMap=new HashMap<Integer, TextView>();
		textleft_ToMap.put(R.id.button_open001, textleft_to1);
		textleft_ToMap.put(R.id.button_open002, textleft_to2);
		textleft_ToMap.put(R.id.button_open003, textleft_to3);
		textleft_ToMap.put(R.id.button_open004, textleft_to4);
		textleft_ToMap.put(R.id.button_open005, textleft_to5);
		textleft_ToMap.put(R.id.button_open006, textleft_to6);
		textleft_ToMap.put(R.id.button_open007, textleft_to7);
		textleft_ToMap.put(R.id.button_open008, textleft_to8);
		textleft_ToMap.put(R.id.button_open009, textleft_to9);
		textleft_ToMap.put(R.id.button_open010, textleft_to10);
		
		imagePosition=new HashMap<Integer,Integer>();
		imagePosition.put(R.id.button_open001, 0);
		imagePosition.put(R.id.button_open002, 1);
		imagePosition.put(R.id.button_open003, 2);
		imagePosition.put(R.id.button_open004, 3);
		imagePosition.put(R.id.button_open005, 4);
		imagePosition.put(R.id.button_open006, 5);
		imagePosition.put(R.id.button_open007, 6);
		imagePosition.put(R.id.button_open008, 7);
		imagePosition.put(R.id.button_open009, 8);
		imagePosition.put(R.id.button_open010, 9);
		
		ImageView imageright1  = (ImageView) findViewById(R.id.Imageright1);
		ImageView imageright2  = (ImageView) findViewById(R.id.Imageright2);
		ImageView imageright3  = (ImageView) findViewById(R.id.Imageright3);
		ImageView imageright4  = (ImageView) findViewById(R.id.Imageright4);
		ImageView imageright5  = (ImageView) findViewById(R.id.Imageright5);
		ImageView imageright6  = (ImageView) findViewById(R.id.Imageright6);
		ImageView imageright7  = (ImageView) findViewById(R.id.Imageright7);
		ImageView imageright8  = (ImageView) findViewById(R.id.Imageright8);
		ImageView imageright9  = (ImageView) findViewById(R.id.Imageright9);
		ImageView imageright10  = (ImageView) findViewById(R.id.Imageright10);
		
		imageRightMap=new HashMap<Integer, ImageView>();
		imageRightMap.put(R.id.button_open001, imageright1);
		imageRightMap.put(R.id.button_open002, imageright2);
		imageRightMap.put(R.id.button_open003, imageright3);
		imageRightMap.put(R.id.button_open004, imageright4);
		imageRightMap.put(R.id.button_open005, imageright5);
		imageRightMap.put(R.id.button_open006, imageright6);
		imageRightMap.put(R.id.button_open007, imageright7);
		imageRightMap.put(R.id.button_open008, imageright8);
		imageRightMap.put(R.id.button_open009, imageright9);
		imageRightMap.put(R.id.button_open010, imageright10);
//		 
		search_content  = (EditText) findViewById(R.id.search_content);
		search_content.setHint(R.string.seach_text);
		search_content.setOnTouchListener(new HomeOnTouchListener());
		findViewById(R.id.center_icon).setVisibility(View.VISIBLE);
		
		search_view = (View)findViewById(R.id.search_view);
		search_btn  = (Button) findViewById(R.id.search_btn);
		search_btn.setOnClickListener(this);
		TVtitle  = (TextView) findViewById(R.id.text_center);
		TVtitle.setText("手机买团购");
		TVtitle.setOnClickListener(this);
		hotPlace  = (View) findViewById(R.id.titleRightView);
		hotPlace.setVisibility(View.GONE);
		BTNcity  = (TextView) findViewById(R.id.title_btn_left);
		leftView  = (LinearLayout) findViewById(R.id.titleLeftView);
		leftView.setOnClickListener(this);
		findViewById(R.id.title_left_icon).setVisibility(View.VISIBLE);
//	 
		for(int i=0;i<13;i++){
			dataSource.add(new ArrayList<Shop>());
		}
		
		
		bottom_line =(View)findViewById(R.id.bottom_line);
	    bottom_text =(TextView)findViewById(R.id.bottom_text);
	    Button  bottom_button =(Button)findViewById(R.id.bottom_button);
	    bottom_button.setOnClickListener(this);
	    getCityResult();
		
		Intent intent_open = new Intent(this, ShoppingsActivity.class);
		intent_open.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	    parentMainTab.mHost.addTab( parentMainTab.mHost
	            .newTabSpec("Shoppings_tab")
	            .setIndicator("Shoppings",
	                    getResources().getDrawable(R.drawable.icon))
	            .setContent(intent_open));
	    searchListView = (ListView)findViewById(R.id.search_record);
	    searchAdapter=new SearchAdapter(this,recordSearh);
	    searchListView.setAdapter(searchAdapter);
	    searchListView.setOnItemClickListener(this);
	    (((RadioButton) findViewById(R.id.search_history))).setOnCheckedChangeListener(this);
	    (((RadioButton) findViewById(R.id.search_remen))).setOnCheckedChangeListener(this);;
	}
	private TimerTask getAdvertisingTask() {
		TimerTask task=new TimerTask() {
			
			public void run() {
				// TODO Auto-generated method stub
					if(refreshAds){
							if(getNetConnectState(HomeActivity.this)){
								MResult result = ServerService.getAdvertisings(adsList);
								if(result!=null){
									if(result.isSuccess()){
										mTimeoutHandler.sendEmptyMessage(1);
									}
								}
								for(int i=0;i<adsList.size();i++){
									LoadImageFromUrl(adsList.get(i) ,HomeActivity.this);
								}
						}
					}
					mTimeoutHandler.sendEmptyMessage(0);
					i++;
				}
			};
			return task;
		}
		
		public static void setOriginViews(){
			for(int i=0;i<5;i++){
				if(adsList.size()>0){
					if(i<adsList.size()){
						originViews[i].setVisibility(View.VISIBLE);
					}else{
						originViews[i].setVisibility(View.GONE);
					}
				}else{
					if(i<adsDrawableList.size()){
						originViews[i].setVisibility(View.VISIBLE);
					}else{
						originViews[i].setVisibility(View.GONE);
					}
				}
			}
		}
		
	 	public static boolean getNetConnectState(Context context) {
			boolean netConnect = false;
			ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo infoM = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (info.isConnected() || infoM.isConnected()) {
				netConnect = true;
			}
			return netConnect;
		}
 

		  public class ImageAdapter extends BaseAdapter {
		        int mGalleryItemBackground;
		        public ImageAdapter(Context c) {
		            mContext = c;
		        }
		        public int getCount() {
		            return Integer.MAX_VALUE;
		        }
		        public Object getItem(int position) {
		            return position;
		        }
		        public long getItemId(int position) {
		            return position;
		        }
		        public View getView(int position, View convertView, ViewGroup parent) {
		            ImageView image = new ImageView(mContext);
		            if(!(adsList.size()>0)){
		            	image.setImageDrawable(adsDrawableList.get(position % adsDrawableList.size()));
		            }else{
	            	Drawable drawable=adsList.get(position % adsList.size()).getDrawable();
	            	if(drawable!=null){
	            		image.setImageDrawable(drawable);
	            	}else {
	            		LoadImageFromUrl(adsList.get(position % adsList.size()) ,HomeActivity.this);
	            		image.setImageDrawable(HomeActivity.this.getResources().getDrawable(R.drawable.homeload_small));
//		            		ServerService.sirectLoadImageFromUrl(adsList.get(position % adsList.size()) ,HomeActivity.this);
	            	}
	            }
	            image.setScaleType(ImageView.ScaleType.FIT_XY);
	            image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
	            if(!(adsList.size()>0)){
		            for(int i=0;i<originViews.length;i++){
		            	if(i==(position % adsDrawableList.size())){
		            		originViews[i].setBackgroundResource(R.drawable.origintwo);
		            	}else {
		            		originViews[i].setBackgroundResource(R.drawable.originone);
		            	}
		            }
		    
	            }else{
	            	for(int i=0;i<originViews.length;i++){
		            	if(i==(position % adsList.size())){
		            		originViews[i].setBackgroundResource(R.drawable.origintwo);
		            	}else {
		            		originViews[i].setBackgroundResource(R.drawable.originone);
		            	}
		            }
//		            	
	            }
	            return image;
	        }
			private Context mContext;
	 
	    }
	
	
	public class HomeOnTouchListener implements OnTouchListener{
		
		public boolean onTouch(View v, MotionEvent event) {
			// TODO Auto-generated method stub
		  search_view.setVisibility(View.VISIBLE);
		  if(record.trim().length()>=1){
			  recordSearh = record.split("/");
			  searchAdapter.setDate(recordSearh);
			  searchAdapter.notifyDataSetChanged();
			  
		  }else{
			  searchAdapter.setDate(new String[]{});
			  searchAdapter.notifyDataSetChanged();
			  TextView tv = (TextView)HomeActivity.this.findViewById(R.id.shopping_empty);
			  searchListView.setEmptyView(tv);
			  
		  }
		  return false;
		 }
		}
	public void onClick(View v) {
		if(v.getId()==R.id.search_btn){
			MSystem.pv+=1;
			String keyword=  search_content.getText().toString();
			if(!keyword.equals("")){
				Intent intent = new Intent(HomeActivity.this, ShoppingsActivity.class);
				intent.putExtra("keyword",keyword);
				intent.putExtra("type","11");
				dataType = 11;
				HomeActivity.this.startActivity(intent);
				String newRecord="";
				if(record.contains(keyword)){
					String temp = new String(record.replace(new String(keyword+"/"), ""));
					newRecord = keyword+"/"+temp.trim();
				}else{
					newRecord= keyword+"/"+record;
				}
				record=newRecord;
				recordSearh=newRecord.split("/");
				searchAdapter.setDate(recordSearh);
				searchAdapter.notifyDataSetChanged();
				preFerence.edit().putString("recordSearh", newRecord).commit();
				((InputMethodManager) HomeActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE))//
			        .hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); 
			}else{
				Toast.makeText(HomeActivity.this,R.string.seach_text_not_date, 1).show();
			}
		}else if(v.getId()==R.id.titleLeftView){
			MSystem.pv+=1;
			Intent intents = new Intent(HomeActivity.this, HotPlaceActivity.class);
			HomeActivity.this.startActivityForResult(intents,2);
		}else if(v.getId()==R.id.text_center){
			MSystem.pv+=1;
			Intent intents = new Intent(HomeActivity.this, ChangeCityActivity.class);
			intents.putExtra("from", "home");
			HomeActivity.this.startActivityForResult(intents,1);
		}else if(v.getId()==R.id.bottom_button){
			 num=11;
			 MSystem.edit+=MSystem.edit;
			 LocationService locationService = new LocationService(HomeActivity.this);
			 locationService.start();
			 getCityResult();
		}else{
			MSystem.pv+=1;
			switch (v.getId()) {
			case R.id.button_open001: 	
				 dataType = 1;
				break;
			case R.id.button_open002: 
				 dataType = 2;
				 break;
			case R.id.button_open003: 
				 dataType = 3;
				break;
			case R.id.button_open004: 
				dataType = 4;
				break;
			case R.id.button_open005: 
				dataType = 5;
				break;
			case R.id.button_open006: 	
				dataType = 6;
				break;
			case R.id.button_open007: 
				dataType = 7;
				break;
			case R.id.button_open008: 	
				dataType = 8;
				break;
			case R.id.button_open009: 	
				dataType = 9;
				break;
			case R.id.button_open010: 
				dataType = 10;
				break;
	 
			}
			 parentMainTab.mHost.setCurrentTabByTag("Shoppings_tab");
		}
	}
	public void search_item_city(){
		Dialog dialog = null;
		Builder b2 = new AlertDialog.Builder(this);
		b2.setTitle(R.string.selected_city);
        b2.setItems(R.array.hot_place_city, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	String[] citys= getResources().getStringArray(R.array.hot_place_city);
            	String city = citys[which].replace("　","");
            	TVtitle.setText(city);
            	MSystem.selectCity = city;
            }
        });
        dialog = b2.create();
        dialog.show();
	}

	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
	}

public class HomeOnItemClick implements OnItemClickListener{
	
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		MSystem.pv+=1;
		// TODO Auto-generated method stub
		if(adsList.size()>0){
			int temp = position %adsList.size();
			if(temp<=adsList.size()){
				try{
				 //url为你要链接的地址
						if (adsList.get(temp).getLink_type().trim().equals("coupon")) {
							final String cid = adsList.get(temp).getLink_url();
							executorService.execute(new Thread() {
								
								public void run() {
									// TODO Auto-generated method stub
									super.run();
									try {
										Shop shop = new Shop();
										MResult mResult = MSystem.getShopDetail(shop, cid);
										if (shop != null) {
											Intent intent = new Intent(HomeActivity.this, OrderDetailShopActivity.class);
											intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
											intent.putExtra("shop", shop);
											HomeActivity.this.startActivity(intent);
										} else {
											Toast.makeText(HomeActivity.this, "亲，不能打开新团购哦..", 1).show();
										}

									} catch (Exception e) {
										e.printStackTrace();
										// TODO: handle exception
									}

								}
							});

						}else if(adsList.get(temp).getLink_type().trim().equals("category")){
						final String cid=adsList.get(temp).getLink_url();
						int type;
						try{
							type=Integer.parseInt(cid);
							tempdataType=type;
						}catch (Exception e) {
							// TODO: handle exception
							e.printStackTrace();
							type=1;
							tempdataType = type;
						}
						HomeActivity.dataSource.get(HomeActivity.dataType).clear();
						HomeActivity.dataPage[HomeActivity.dataType]=1;
						isload[dataType] = true;
						dataType = 12 ;
						parentMainTab.mHost
							.setCurrentTabByTag("Shoppings_tab");
					}else{
						Intent intent =new Intent(Intent.ACTION_VIEW, Uri.parse(adsList.get(temp).getLink_url()));
						HomeActivity.this.startActivity(intent);
					}
				}catch(Exception e){
//						Toast.makeText(Home.this, "连接不存在", 1).show();
					e.printStackTrace();
				}
			}
		}
	}
}



protected void onResume() {
	// TODO Auto-generated method stub
	super.onResume();
	Boolean clear = false;
	if(MSystem.selectCity.equals("")){
		TVtitle.setText("城市");
	}else{
		TVtitle.setText(MSystem.selectCity);
	}
	if(!(areaName.trim().equals(MSystem.areaName.trim())))
	{
		area=MSystem.area.trim();
		areaName=MSystem.areaName.trim();
		clear=true;
	}
	if(!(selectCity.trim().equals(MSystem.selectCity.trim())))
	{
		area="";
		MSystem.area="";
		MSystem.areaName="";	
		selectCity=MSystem.selectCity.trim();
		clear=true;
	}
	if(!(area.trim().equals(""))){
		BTNcity.setText((MSystem.areaName.split("/")[0]));
	}else{
		BTNcity.setText("商圈");
	}
	if(clear){
		initDataSource();
	}
	if(!isShow){
		num=11;
		getCityResult();
	}
	
}
	private void initDataSource() {
		// TODO Auto-generated method stub
		for(int i=0;i<dataSource.size();i++){
			dataSource.get(i).clear();
			dataPage[i]=1;
			isload[i]=true;
			recordError.clear();
		}
	}
	
	    public boolean onKeyDown(int keyCode, KeyEvent event) {
	    	if (keyCode == KeyEvent.KEYCODE_BACK) {
	    		if(search_view.isShown()){
	    			search_view.setVisibility(View.GONE);
	    		}else{
		    		if (mPop!=null && mPop.isShowing()) {
						mPop.dismiss();
						isFirst = false;
					}else{
						isFirst = true;
						
					}
		    		SharedPreferences sp = HomeActivity.this.getSharedPreferences("user", Context.MODE_PRIVATE);
					size = sp.getInt("size", 0);
		    		LayoutInflater factory=LayoutInflater.from(HomeActivity.this);
					mView =factory.inflate(R.layout.dialog,null);
					checkBox = ((CheckBox)mView.findViewById(R.id.shortcut));
					layout_shortcut = ((LinearLayout)mView.findViewById(R.id.layout_shortcut));
					if(size==1){
						checkBox.setVisibility(View.GONE);
						layout_shortcut.setVisibility(View.GONE);
					}
		    		mPop = new PopupWindow(mView,LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		    		mPop.setAnimationStyle(R.style.dialogWindowAnim);
		    		((Button) mView.findViewById(R.id.ok))
					.setOnClickListener(new OnClickListener() {
						
						public void onClick(View v) {
							//--------------------保存统计数据---------------------
							MSystem.last_end_time = Math.round(new Date().getTime()/1000);
							SharedPreferences sp = HomeActivity.this.getSharedPreferences("user", Context.MODE_PRIVATE);
							Editor edit = sp.edit();
							edit.putString("last_end_time",MSystem.last_end_time+"");
							edit.putString("last_start_time",MSystem.last_start_time+"");
							edit.putString("pv",MSystem.pv+"");
							edit.putString("buy",MSystem.buy+"");
							edit.putString("detail",MSystem.detail+"");
							edit.putString("edit",MSystem.edit+"");
							edit.commit();
							//--------------------创建快捷方式---------------------
							if(size!=1&&checkBox.isChecked()){
								createShortCut();
							}
							
							//----------------------退出应用-----------------------
							android.os.Process.killProcess(android.os.Process.myPid());
							System.exit(0);
							mPop.dismiss();

						}
					});
		    		((Button) mView.findViewById(R.id.cancel))
					.setOnClickListener(new OnClickListener() {
						
						public void onClick(View v) {
							mPop.dismiss();
						}
					});
	    			if(isFirst){
	    				mPop.setOutsideTouchable(true);
	    				mPop.setBackgroundDrawable(new BitmapDrawable());
	    				mPop.showAtLocation(mView, Gravity.CENTER, 0, 0);
	    				isFirst = false;
	    			}
	    		}
	    		return true;
		    }else{
		    	return super.onKeyDown(keyCode, event);
		    }
	    }
		public void setShadow(Boolean isTransparent){
			WindowManager.LayoutParams lp=getWindow().getAttributes();
			if(isTransparent){
		        lp.alpha=0.3f;
		        lp.dimAmount=0.3f;
		        getWindow().setAttributes(lp);
		        getWindow().setAttributes(lp);
			}else{
				lp.alpha=1.0f;
		        lp.dimAmount=1.0f;
		        getWindow().setAttributes(lp);
		        getWindow().setAttributes(lp);
			}

		}
	
	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			  int position;
			  position= imagePosition.get(v.getId());
			  imageLeftMap.get(v.getId()).setImageResource(leftPressedImages[position]);
			  imageRightMap.get(v.getId()).setVisibility(View.GONE);
			  textleftMap.get(v.getId()).setTextColor(Color.WHITE);
			  textleft_ToMap.get(v.getId()).setTextColor(Color.WHITE);
			break;
		case MotionEvent.ACTION_CANCEL:
			  int cancelPosition;
			 
			  cancelPosition= imagePosition.get(v.getId());
			  imageLeftMap.get(v.getId()).setImageResource(leftNormalImages[cancelPosition]);
			  imageRightMap.get(v.getId()).setVisibility(View.VISIBLE);
			  textleftMap.get(v.getId()).setTextColor(Color.BLACK);
			  textleft_ToMap.get(v.getId()).setTextColor(Color.BLACK);
			break;
		case MotionEvent.ACTION_UP:
			  int upPosition;
			  upPosition= imagePosition.get(v.getId());
			  imageLeftMap.get(v.getId()).setImageResource(leftNormalImages[upPosition]);
			  imageRightMap.get(v.getId()).setVisibility(View.VISIBLE);;
			  textleftMap.get(v.getId()).setTextColor(Color.BLACK);
			  textleft_ToMap.get(v.getId()).setTextColor(Color.BLACK);
			break;

		default:
			break;
		}
		return false;
	}
	
	public static void saveBitMap(Bitmap bitmap, String filePath)
    throws IOException, FileNotFoundException {
		File fp = new File("/sdcard/tuangou");
		File file = new File("/sdcard/tuangou/.nomedia");
		if (!fp.exists()) {
			fp.mkdir();
			if((!file.exists())){  
				file.createNewFile();
			}
		}else{
			File f = new File(filePath);
			f.createNewFile();
			FileOutputStream fos = new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
			fos.flush();
			fos.close();
		}
}
	public class SearchAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private String[] record;
		
		public SearchAdapter(Activity a,String[] record) {
			this.mInflater = LayoutInflater.from(a);
			this.record=record;
		}
		public int getCount() {
			 
		     return record.length;
		}

		public void setDate(String[] objects) {
			this.record=objects;
		}
		
		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
				convertView = mInflater.inflate(R.layout.search_item, null);
				TextView text=(TextView)convertView.findViewById(R.id.record_text);
				if(record.length>0){
					text.setText(record[position]);
				}
				return convertView;
		}


	}
    private void LoadImageFromUrl(final Advertising advertising,
			HomeActivity homeActivity) {
		// TODO Auto-generated method stub
		String filePath = "/sdcard/tuangou/"+advertising.getId()+"small.jpg";
		File file=new File(filePath);
		if(file.exists()){
			try{
				Drawable drawable=Drawable.createFromPath(filePath);
				if(drawable!=null){
					advertising.setDrawable(drawable);
				}else{
					file.delete();
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			executorService.execute(new Thread() {
				
				public void run() {
					InputStream is = null;
					Drawable drawable = null;
					if (getNetConnectState(HomeActivity.this)) {
						try {
							Drawable sirectDrawable = null;
							HttpURLConnection conn = Util.getHttpURLConnection(advertising.getImage_url());
							conn.setDoInput(true);
							if (conn.getResponseCode() == 200) {
								is = conn.getInputStream();
								int size = conn.getContentLength();
								if (is != null) {
									Bitmap bitmap = BitmapFactory.decodeStream(is);
									drawable = new BitmapDrawable(bitmap);
									sirectDrawable = drawable;
									advertising.setDrawable(drawable);
									if (sirectDrawable != null && size > 4) {
										try {
											String filePath = "/sdcard/tuangou/" + advertising.getId() + "small.jpg";
											saveBitMap(bitmap, filePath);
										} catch (Exception e) {
											e.printStackTrace();
										}
									}
								}
							}
						} catch (Exception e1) {
							e1.printStackTrace();
						}
					}
				}
			});
				 
			// TODO: handle exception
		}
	}
	public void createShortCut(){
    	SharedPreferences sp = this.getSharedPreferences("user", Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putInt("size", 1);
		edit.commit();
		//创建快捷方式的Intent
         Intent shortcutIntent = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");
         shortcutIntent.getBooleanExtra("duplicate", false);
         //不允许重复创建
         shortcutIntent.putExtra("duplicate",false);
         //需要现实的名称
         shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
         //快捷图片
         Parcelable icon = Intent.ShortcutIconResource.fromContext(getApplicationContext(), R.drawable.icon);
         shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
         //点击快捷图片，运行的程序主入口
         shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(getApplicationContext() , WelcomeActivity.class));
         //发送广播
         sendBroadcast(shortcutIntent);
    }
	
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		MSystem.pv+=1;
		// TODO Auto-generated method stub
		Intent intent = new Intent(HomeActivity.this, ShoppingsActivity.class);
		if(search){
			intent.putExtra("keyword",recordSearh[position]);
		}else{
			intent.putExtra("keyword",mHot.get(position));
		}
		intent.putExtra("type","11");
		dataType = 11;
		HomeActivity.this.startActivity(intent);
	}
 
	
	public void onCheckedChanged(CompoundButton buttonView,
			boolean isChecked) {
		MSystem.pv+=1;
		// TODO Auto-generated method stub
	 	if (isChecked) {
    		 switch (buttonView.getId()) {
	    		 case R.id.search_history:
	    			 	search=true;
	    			 	 if(record.trim().length()>=1){
	    					  recordSearh = record.split("/");
	    					  searchAdapter.setDate(recordSearh);
	    					  searchAdapter.notifyDataSetChanged();
	    				  }else{
	    					  
	    					 
	    					  searchAdapter.setDate(new String[]{});
	    					  searchAdapter.notifyDataSetChanged();
	    					  TextView tv = (TextView)HomeActivity.this.findViewById(R.id.shopping_empty);
	    					  searchListView.setEmptyView(tv);
	    				  }
	                 break;
	    		 case R.id.search_remen:
	    			 	search=false;
	    			 	if(!(mHot.size()>1)){
		    			 	searchtimer=new Timer();
		    			 	TimerTask task=new TimerTask() {
		    					
		    					public void run() {
		    						// TODO Auto-generated method stub
    								if(getNetConnectState(HomeActivity.this)){
    									MResult result =MSystem.getHotWord(mHot);;
    									if(result!=null){
    										if(result.isSuccess()){
    											 searchtimer.cancel();
    					    			 		 mTimeoutHandler.sendEmptyMessage(4);
    											}
    									}
		    						}
		    					}
		    				};
		    				searchtimer.schedule(task, 0,6000);
	    			 	}else{
	    			 		  String []temp =new String[mHot.size()];
	    			 		  for(int i=0;i<mHot.size();i++){
	    			 			 temp[i]=mHot.get(i);
	    			 		  }
	    			 		  searchAdapter.setDate(temp);
	    					  searchAdapter.notifyDataSetChanged();
	    			 	}
	                 break;
    		 }
	 	}
	}
    public static Handler mTimeoutHandler = new Handler() {
	        
	        public void handleMessage(Message msg) {
	        	super.handleMessage(msg);
	        	switch (msg.what) {
				case 0:
					imageAdsGallery.setSelection(i);
					break;
				case 1:
					if(adsList.size()>0){
						refreshAds=false;
					}
					setOriginViews();
					imageAdapter.notifyDataSetChanged();
					break;
				case 2:
				    setOriginViews();
					imageAdapter.notifyDataSetChanged();
					break;
				case 3:
					TVtitle.setText(MSystem.mLocation.getCity());
					break;
				case 4:
					 String []temp =new String[mHot.size()];
			 		 for(int i=0;i<mHot.size();i++){
			 			 temp[i]=mHot.get(i);
			 		 }
			 		 searchAdapter.setDate(temp);
  					 searchAdapter.notifyDataSetChanged();
					break;
					
					
				case 8:
					if(MSystem.mLocation!= null){
						if(isNull(MSystem.mLocation.getCity())){
							bottom_text.setText(MSystem.mLocation.getAddress().trim());
							bottom_line.setVisibility(View.VISIBLE);
							isShow=true;
							if(bottomTimer!=null){
								num=11;
							}
						}
					}else{
						if(locating>0){
							bottom_text.setText("                正在定位中,请稍候...");
							bottom_line.setVisibility(View.VISIBLE);
						}else{
							bottom_line.setVisibility(View.GONE);
						}
					}
					break;
				case 7:
						bottom_line.setVisibility(View.GONE);
						break;
				default:
					break;
				}  
	        }
	    };
	    
		public Handler mHander = new Handler(){
			
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				if(msg.what==0){
					if(isVersion){
						showUpdate();
					}
				}else {
					bottom_line.setVisibility(View.GONE);
					Intent intents = new Intent(HomeActivity.this, ChangeCityActivity.class);
					intents.putExtra("from", "home");
					HomeActivity.this.startActivity(intents);
				}
			}
		};
		public static  Boolean isNull(String str){
			if(str!=null&&!str.equals("")&&str!=""&&!str.equals("null")){
				return true;
			}
			return false;
		}
		
		public void getCityResult() {
			if (bottomTimer != null) {
				bottomTimer.cancel();
			}
			TimerTask task = new TimerTask() {
				public void run() {
					locating--;
					if(!isShow){
						mTimeoutHandler.sendEmptyMessage(8);
						if(locating==0){
							mHander.sendEmptyMessage(2);
						}
					}else{
						num--;
						if(num==0){
							bottomTimer.cancel();
							mTimeoutHandler.sendEmptyMessage(7);
						}
					}
					
				}
			};
			bottomTimer = new Timer();
			bottomTimer.schedule(task, 0, 1000);
		}
}
